package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionhandler {
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e) {
        log.error("服务器发生异常:{}", e);
        return Result.error("您的网络发生异常,请稍后再试....");
    }

    @ExceptionHandler(RuntimeException.class)
    public Result handlerRuntimeException(RuntimeException e) {
        //log.error("服务器发生异常:{}", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler
    public Result DuplicateHandler(DuplicateKeyException e) {
        String message = e.getMessage();
        int duplicateEntry = message.indexOf("Duplicate entry");
        String substring = message.substring(duplicateEntry);
        String[] split = substring.split(" ");
        String s = split[2];
        return Result.error(s + "重复");
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
        Map<String, String> paramNameMap = new HashMap<>();
        paramNameMap.put("score", "违纪扣分");

        String paramName = ex.getName(); // 获取参数名
        String chineseName = paramNameMap.getOrDefault(paramName, paramName);
        String message = chineseName + "不能为空";

        return Result.error(message);
    }
}
